package com.edooteach.api.web.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.edoomath.entity.user.User;
import com.edooteach.api.handler.SmsSender;
import com.edooteach.api.servcice.UserService;

/**
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("/sms")
public class SmsController {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsController.class);
    
    @Autowired
    private SmsSender smsSender;
    
    @Autowired
    private UserService userService;
    
    @RequestMapping(value = "/verify-user-code", method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult verifyUserCode(@RequestParam("mobile") String mobile) {
    	
    	HttpResult httpResult = new HttpResult();
    	
    	try {
    		
    		User user = userService.loadByMobile(mobile);
    		
    		if(user ==  null) {
    			logger.error("#sendVerifyCode() no user with such mobile [{}]", mobile);
                httpResult.fail("501").message("该手机用户不存在");
                return httpResult;
    		}
    		
    		// Generate random code in 6 digits
            String code = smsSender.generateVerifyCode(mobile);
            boolean send = smsSender.sendVerifyCode(mobile, code);
            
            if(send) {
                String token = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, "edooteach"));
                httpResult.success()
                          .data("token", token)
                          .message("发送短信成功");
            } else {
                logger.error("#sendVerifyCode() faild with response [{}]", JsonUtils.toJson(httpResult));
                httpResult.fail("501").message("发送短息失败");
            }
    		
    		
    	} catch (Exception e) {
            
            logger.error("#sendVerifyCode() occurs error", e);
            
            httpResult.fail("500").message("发送短息请求失败");
        }
        
        return httpResult;
    	
    }
    
    /**
     * 
     * @param mobile
     * @param token
     * @param code
     * @return 
     */
    @RequestMapping(value = "/verify-user-mobile", method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult verifyUserMobile(@RequestParam("unionid") String unionid,
    								   @RequestParam("mobile") String mobile,
    								   @RequestParam("token") String token,
    								   @RequestParam("code") String code) {
    	
    	HttpResult httpResult = new HttpResult();
    	
    	try {
    		
    		boolean result = smsSender.checkVerifyCode(mobile, code, token);
    		
    		if(!result) {
    			httpResult.fail("500").message("验证码不正确");
    			return httpResult;
    		}
    		
    		User user = userService.load(unionid);
    		if(org.apache.commons.lang3.StringUtils.isBlank(user.getMobile())) {
    			userService.bindUserMobile(user, mobile);
    		}
    		
    		httpResult.success().message("验证用户手机成功");
    		
    	} catch (Exception e) {
    		
    		logger.error("#verifyUserMobile() occurs error", e);
            
            httpResult.fail("500").message("验证用户手机失败");
    		
    	}
    	
    	return httpResult;
    }	
    
    /**
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/verify-code", method = RequestMethod.POST,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult sendVerifyCode(@RequestParam("mobile") String mobile) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            // Generate random code in 6 digits
            String code = smsSender.generateVerifyCode(mobile);
            boolean send = smsSender.sendVerifyCode(mobile, code);
            
            if(send) {
                String token = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, "edooteach"));
                httpResult.success()
                          .data("token", token)
                          .message("发送短信成功");
            } else {
                logger.error("#sendVerifyCode() faild with response [{}]", JsonUtils.toJson(httpResult));
                httpResult.fail("501").message("发送短息失败");
            }
            
        } catch (Exception e) {
            
            logger.error("#sendVerifyCode() occurs error", e);
            
            httpResult.fail("500").message("发送短息请求失败");
        }
        
        return httpResult;
    }
    
}
